library(tidyverse)
library(gt)
library(readxl)

Reading in the data

The Excel file read in this example is analytic_data.xlxs. Replace this with your Excel file.

In this R Markdown file, the data frame is called EXAMPLE_DATA. Replace this with the name of the file you wish to use.

EXAMPLE_DATA <- read_excel("analytic_data.xlsx")
EXAMPLE_DATA <- EXAMPLE_DATA %>% 
  mutate_if(is.character,as.factor)

The examples here will use a summarised data frame created from EXAMPLE_DATA. In all of the code below, you will need to replace SUMMARISED with the name of your data frame. You will need to use the appropriate variable names.

SUMMARISED_DATA <- EXAMPLE_DATA %>%
  group_by(CATEGORICAL_VARIABLE1, CATEGORICAL_VARIABLE2) %>%
  summarise(
    mean_NV1 = mean(NUMERICAL_VARIABLE1),
    sd_NV1 = sd(NUMERICAL_VARIABLE1)
  ) %>%
  ungroup()
## `summarise()` has grouped output by 'CATEGORICAL_VARIABLE1'. You can override
## using the `.groups` argument.

Making a table from a data frame

SUMMARISED_DATA %>%
  gt()
CATEGORICAL_VARIABLE1 CATEGORICAL_VARIABLE2 mean_NV1 sd_NV1
A N 4.750000 0.212132
A Y 3.775000 1.492601
B N 4.857143 2.821263
B Y 4.366667 3.817504

Controlling decimal places

SUMMARISED_DATA %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2)
CATEGORICAL_VARIABLE1 CATEGORICAL_VARIABLE2 mean_NV1 sd_NV1
A N 4.75 0.21
A Y 3.77 1.49
B N 4.86 2.82
B Y 4.37 3.82

Alignment of columns

SUMMARISED_DATA %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2) %>%
  cols_align("left", columns = c(CATEGORICAL_VARIABLE1, CATEGORICAL_VARIABLE2))
CATEGORICAL_VARIABLE1 CATEGORICAL_VARIABLE2 mean_NV1 sd_NV1
A N 4.75 0.21
A Y 3.77 1.49
B N 4.86 2.82
B Y 4.37 3.82

Column headings

SUMMARISED_DATA %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2) %>%
  cols_label(
    CATEGORICAL_VARIABLE1 = "First variable",
    CATEGORICAL_VARIABLE2 = "Second variable",
    mean_NV1 = "NV1 (Mean)",
    sd_NV1 = "NV1 (SD)"
  )
First variable Second variable NV1 (Mean) NV1 (SD)
A N 4.75 0.21
A Y 3.77 1.49
B N 4.86 2.82
B Y 4.37 3.82

Grouping rows

SUMMARISED_DATA %>%
  group_by(CATEGORICAL_VARIABLE1) %>%
  gt() %>%
  fmt_number(c(mean_NV1, sd_NV1), decimals = 2)
CATEGORICAL_VARIABLE2 mean_NV1 sd_NV1
A
N 4.75 0.21
Y 3.77 1.49
B
N 4.86 2.82
Y 4.37 3.82

© Statistical Consulting Centre, University of Melbourne, 2023